package com.sxj.springsourcecode.springframework.utils;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ProjectName: spring-source-code
 * @Package: com.sxj.springsourcecode.springframework.utils
 * @ClassName: ClassUtil
 * @Author: sxj
 * @Description:
 * @Date: 2024/2/21 14:26
 * @Version: 1.0.0
 */
@Slf4j
public class ClassUtil {
    /**
     * 设置给定字段的值
     * @param clz
     * @param bean
     * @param fieldName
     * @param value
     */
    public static void setFeildValue(Class clz,Object bean,String fieldName,Object value){
        try {
            Field field = clz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(bean,value);
        } catch (NoSuchFieldException e) {
            log.info("没有指定的【{}】字段属性！",fieldName);
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            log.info("设置字段【{}】属性出错！",fieldName);
            e.printStackTrace();
        }
    }

    /**
     * 调用指定的方法
     * @param clz
     * @param bean
     * @param methodName
     */
    public static void invokeMethod(Class clz,Object bean,String methodName){
        try {
            Method method = clz.getDeclaredMethod(methodName);
            method.invoke(bean);
        } catch (NoSuchMethodException e) {
            log.info("没有指定的【{}】方法！",methodName);
            e.printStackTrace();
        } catch (InvocationTargetException |IllegalAccessException  e) {
            log.info("调用方法【{}】出错！",methodName);
            e.printStackTrace();
        }
    }
}
